<template>
    <el-upload class="upload" v-model:file-list="files" :action="uploadUrl" :before-upload="beforeUpload" :headers="headers"
        :on-success="handleSuccess" :on-error="handleError" list-type="text" :drag="item.drag" v-bind="item.props"
        v-on="item.props">
        <div v-if="item.drag">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                拖拽文件 或 <em>点击上传</em>
            </div>
        </div>
        <el-button v-else>点击上传</el-button>
        <template #tip>
            <div class="el-upload__tip">
                {{ item.placeholder }}
            </div>
        </template>
    </el-upload>
</template>

<script lang="ts" setup>
import { uploadUrl } from "../config";
import { computed } from "vue";
import { IFormItem } from '../type';
import { UploadFilled } from '@element-plus/icons-vue';
import { ElMessage, UploadFile, UploadFiles } from "element-plus";

// TODO: 通过file插槽,美化已上传文件列表
interface IProps {
    item: IFormItem;
    modelValue: any;
}
interface IEmit {
    (event: 'update:modelValue', data: any): void
}
const props = defineProps<IProps>()
const emit = defineEmits<IEmit>()
const value = computed({
    get() {
        return props.modelValue
    }, set(value) {
        emit('update:modelValue', value)
    }
})
const files = ref<any[]>([])
watch(() => files.value, (val) => {
    value.value = val.map(item => String(item.uid))
})
const headers = reactive({
    token: sessionStorage.getItem('token') || localStorage.getItem('token'),
    fileType: "99",
    fileFlag: ""
})
const beforeUpload = (file: UploadFile) => {

    // 校验文件类型和大小，返回 false 即可阻止上传
    const { size, name, uid } = file
    if (!size) {
        ElMessage.warning('不可上传空文件')
        return false
    } else if (props.item.max && size > props.item.max * 1024) {
        ElMessage.warning('上传文件大小超过最大限制')
        return false
    } else if (files.value.some(item => item.name === name)) {
        ElMessage.warning('已上传同名文件')
        return false
    }

    //添加fileFlag作为文件标识
    headers.fileFlag = String(uid)
}
const handleSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    // 处理成功的回调函数
    ElMessage.success(`${uploadFile.name} 上传成功`)
}
const handleError = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    // 处理失败的回调函数
    ElMessage.error(`${uploadFile.name} 上传失败`)
}
</script>

<style lang="scss" scoped>
.upload {
    width: 100%;
}
</style>